#!/bin/bash

echo "Starting fixed MongoDB sync from source to target..."

# 等待数据库服务启动
echo "Waiting for databases to be ready..."
sleep 15

# 检查源数据库连接
echo "Checking source database connection..."
mongosh --host mongodb-source:27017 --username admin --password password1 --authenticationDatabase admin --eval "db.runCommand('ping')"

if [ $? -ne 0 ]; then
    echo "Error: Cannot connect to source database"
    exit 1
fi

# 检查目标数据库连接
echo "Checking target database connection..."
mongosh --host mongodb-target:27017 --username admin --password password2 --authenticationDatabase admin --eval "db.runCommand('ping')"

if [ $? -ne 0 ]; then
    echo "Error: Cannot connect to target database"
    exit 1
fi

# 检查源数据库数据
echo "Checking source database data..."
SOURCE_COUNT=$(mongosh --host mongodb-source:27017 --username admin --password password1 --authenticationDatabase admin --quiet --eval "
  db = db.getSiblingDB('testdb');
  print(db.users.countDocuments() + db.products.countDocuments() + db.orders.countDocuments());
")

echo "Source database has $SOURCE_COUNT documents"

# 执行全量同步
echo "Starting mongosync full sync..."
mongosync \
    --acceptDisclaimer \
    --cluster0 "mongodb://admin:password1@mongodb-source:27017/admin" \
    --cluster1 "mongodb://admin:password2@mongodb-target:27017/admin" \
    --verbosity INFO

if [ $? -eq 0 ]; then
    echo "Sync completed successfully!"
    
    # 验证同步结果
    echo "Verifying sync results..."
    TARGET_COUNT=$(mongosh --host mongodb-target:27017 --username admin --password password2 --authenticationDatabase admin --quiet --eval "
      db = db.getSiblingDB('testdb');
      print(db.users.countDocuments() + db.products.countDocuments() + db.orders.countDocuments());
    ")
    
    echo "Target database now has $TARGET_COUNT documents"
    
    if [ "$SOURCE_COUNT" -eq "$TARGET_COUNT" ]; then
        echo "✅ Sync verification successful! Document counts match."
    else
        echo "⚠️  Sync verification failed! Document counts don't match."
        echo "Source: $SOURCE_COUNT, Target: $TARGET_COUNT"
    fi
else
    echo "❌ Sync failed!"
    exit 1
fi 